package com.lee.message.core.config.lock.redis;

import com.lee.message.core.config.consts.Consts;
import com.lee.message.core.config.lock.Lock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 基于redis实现分布式锁
 */
@Slf4j
public class RedisLock implements Lock {

    private RedisTemplate redisTemplate;

    public RedisLock(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean tryLock(String key, int lockExpire) {
        return tryLock(key, lockExpire, TimeUnit.SECONDS);
    }

    @Override
    public boolean tryLock(String key, int lockExpire, TimeUnit timeUnit) {
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, Consts.DEFAULT_VAUE, lockExpire, timeUnit);
        } catch (Exception e){
            log.error("访问redis异常", e);
            throw new RuntimeException("访问redis异常", e);
        }
    }

    @Override
    public void unlock(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e){
            log.error("访问redis异常", e);
            throw new RuntimeException("访问redis异常", e);
        }
    }

    @Override
    public boolean exists(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e){
            log.error("访问redis异常", e);
            throw new RuntimeException("访问redis异常", e);
        }
    }
}
